import { Component, OnInit, ViewChild } from '@angular/core';
import { NavController } from '@ionic/angular';
import { CropperComponent } from 'angular-cropperjs';
import { ActivatedRoute } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { WebView } from '@ionic-native/ionic-webview/ngx';
import { HttpService } from 'src/app/service/http.service';
import { MineService } from 'src/app/service/mine.service';

@Component({
  selector: 'app-photo-edit',
  templateUrl: './photo-edit.component.html',
  styleUrls: ['./photo-edit.component.scss'],
})
export class PhotoEditComponent implements OnInit {

  @ViewChild('angularCropper')
  public angularCropper: CropperComponent;//装饰器获取裁剪元素

  imageData: any;

  imageUrl: any = '';

  config: any = {
    viewMode: 1,
    autoCropArea: 0.8,//初始化裁剪框小于图片宽度
    cropBoxResizable: true,
    dragMode: 'move',
    minContainerWidth: document.body.offsetWidth,//容器的最小宽度
    minContainerHeight: document.body.offsetHeight,//容器的最小高度
    aspectRatio: 1, //裁剪框的宽高比
    autoCrop: true, //初始化时，自动生成裁剪框 当初始化时，可以自动生成图像。（就是自动显示裁剪框，改成false裁剪框自动消失
    cropend: function () { // 每次裁剪完毕，获取裁剪后的图片
      // this.getCropperImage();//我在最后点击确定的时候再获取的图片，避免iOS获取黑色图片的问题
    }.bind(this),
    ready: function () {
      // this.getCropperImage(); // 初始化后，自动获取默认裁剪区域的图片
      // iOS这个初始化方法会有问题，如果裁剪框不移动的话，获取到的是一张黑色的图片
    }.bind(this)
  };

  constructor(private activedRoute: ActivatedRoute, private webview: WebView, private domSanitizer: DomSanitizer, private navController: NavController, private httpService: HttpService, private mineService: MineService) { }

  ngOnInit() {
    this.activedRoute.queryParams.subscribe(params => {
      const filePath = params.filePath // filePath 是类似这样的路径：file:///Users/dan/camera-image-12345.png
      if (filePath) {
        let fileUrl = this.webview.convertFileSrc(filePath);
        this.imageUrl = this.domSanitizer.bypassSecurityTrustUrl(fileUrl);
      }
    })
  }

  getCropperImage() {
    const canvasElement = this.angularCropper.cropper.getCroppedCanvas({
      width: 300, // 这里配置的是裁剪后，生成后的图片的大小，width和height至少需要设置一个，否则IOS可能无法生成裁剪图片导致上传文件是失败的，
      height: 300,
      imageSmoothingEnabled: true,
      imageSmoothingQuality: 'high'
    });
    // 生成base64格式图片，可以直接在img标签中展示
    // this.imageData = canvasElement.toDataURL('image/jpeg');
  }

  cancel() {
    this.navController.pop()
    // this.navController.navigateForward('/person-info/photo')
  }

  save() {
    const canvasElement = this.angularCropper.cropper.getCroppedCanvas({
      width: 300, // 这里配置的是裁剪后，生成后的图片的大小，width和height至少需要设置一个，否则IOS可能无法生成裁剪图片导致上传文件是失败的，
      height: 300,
      imageSmoothingEnabled: true,
      imageSmoothingQuality: 'high'
    });
    // blob 测试
    // const blob = new Blob(["Hello World!"], { type: 'text/plain' });
    // console.info(blob);
    // console.info(blob.slice(1, 3, 'text/plain'));
    // this.httpService.uploadPhoto(blob).then(result => {
    //   console.log(result)
    // }).catch(err => {
    //   console.log(err)
    // })
    // 要保存到后台，推荐使用Blob来上传图片
    canvasElement.toBlob(blob => {
      this.httpService.uploadPhoto(blob).then(result => {
        console.log(result)
        const { code, data } = result
        if (code == 0) {
          this.mineService.setPhotoUrl(data)
          this.navController.pop()
        }
      }).catch(err => {
        console.log(err)
      })
    }, "image/jpeg", 0.95)
  }
}
